#include "udpServer.hpp"
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <memory>
using namespace std;
using namespace Server;

static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " lock_port\n\n";
}

// 消息转发
void handlerMessage(const int &sockfd, const string &clientip, const uint16_t &clientport, const string &message)
{
    // 就可以对message进行处理，而不去关心message是怎么来的
    // 从而实现了通信和处理信息的解耦

    // 1.简单的业务逻辑
    string response_message = message;
    response_message+= "[server echo]";
    // 2.将信息转发回客户端
    struct sockaddr_in client;
    bzero(&client, sizeof(client));

    client.sin_family = AF_INET;
    client.sin_port = htons(clientport);
    client.sin_addr.s_addr = inet_addr(clientip.c_str());
    sendto(sockfd, response_message.c_str(), response_message.size(), 0, (struct sockaddr *)&client, sizeof(client));
}


// ./UdpServer ip prot
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<udpserver> usvr(new udpserver(handlerMessage, port));
    usvr->initServer();
    usvr->start();
    return 0;
}
